import React, {useContext, useMemo} from 'react'
import {createForm} from '@formily/core'
import {createSchemaField} from '@formily/react'
import {
    ArrayCards,
    ArrayTable,
    Cascader,
    Checkbox,
    DatePicker,
    Editable,
    Form,
    FormCollapse,
    FormGrid,
    FormItem,
    FormLayout,
    FormTab,
    Input,
    NumberPicker,
    Password,
    PreviewText,
    Radio,
    Reset,
    Select,
    Space,
    Submit,
    Switch,
    TimePicker,
    Transfer,
    TreeSelect,
    Upload
} from '@formily/antd'
import {Button, Card, message, Rate, Result, Slider, Spin} from 'antd'
import {TreeNode} from '@designable/core'
import {transformToSchema} from '@designable/formily'
import {previewProvider} from "../preview";
import {saveTableData} from "../../design/service/api";

const Text: React.FC<{
    content?: string
    mode?: 'normal' | 'h1' | 'h2' | 'h3' | 'p'
}> = ({mode, content, ...props}) => {
    const tagName = mode === 'normal' || !mode ? 'div' : mode
    return React.createElement(tagName, props, content)
}

const SchemaField = createSchemaField({
    components: {
        Space,
        FormGrid,
        FormLayout,
        FormTab,
        FormCollapse,
        ArrayTable,
        ArrayCards,
        FormItem,
        DatePicker,
        Checkbox,
        Cascader,
        Editable,
        Input,
        Text,
        NumberPicker,
        Switch,
        Password,
        PreviewText,
        Radio,
        Reset,
        Select,
        Submit,
        TimePicker,
        Transfer,
        TreeSelect,
        Upload,
        Card,
        Slider,
        Rate,
    },
})

export interface IPreviewWidgetProps {
    tree: TreeNode,
    submit?: Function
}

export const PreviewWidget: React.FC<IPreviewWidgetProps> = (props) => {
    const form = useMemo(() => createForm(), [])
    const {tableName} = useContext(previewProvider)
    const [loading, setLoading] = React.useState(false)
    const [submitted, setSubmitted] = React.useState(false)

    const {form: formProps, schema} = transformToSchema(props.tree, {
        designableFormName: 'Root',
        designableFieldName: 'DesignableField',
    })

    /**
     * 校验表单是否非空
     * @param value
     */
    const isValid = (value: any) => {
        let isEmpty = true
        for (let [_, val] of Object.entries(value)) {
            if (val) isEmpty = false
        }
        if (isEmpty) {
            message.error('请输入数据！')
            return false
        }
        return true
    }

    /**
     * 提交表单
     * @param value
     */
    const submit = async (value: any) => {
        if (!isValid(value)) return
        setLoading(true)
        const submitForm: Record<string, any> = {}
        if (!form.indexes) form.indexes = new Map<string, string>()
        for (const key of form.indexes.keys()) {
            submitForm[key] = ''
        }

        const isUploadFile = (value: any, key: string) => {
            return Array.isArray(value[key]) && value[key].length && value[key][0].thumbUrl && value[key][0].response
        }

        for (const key in value) {
            if (isUploadFile(value, key)) {
                value[key] = value[key].map((item: any) => {
                    return item.response?.data?.blobUrl
                })
                if(value[key].length === 1) value[key] = value[key][0]
            }
        }

        Object.assign(submitForm, value)
        const data = await saveTableData(tableName, submitForm)
        setLoading(false)
        if (!data) return
        message.success('提交成功')
        setSubmitted(true)

        // props.submit && props.submit(submitForm)
    }

    const jumpHome = () => {
        window.location.href = `/#/home`;
    }
    const renderResult = () => {
        return (
            <Result
                status="success"
                title="提交成功!"
                extra={[
                    <Button type="primary" key="console" onClick={jumpHome}>
                        返回主页面
                    </Button>,
                ]}
            />
        )
    }
    return (
        <div style={{padding: '20px'}}>
            {
                !submitted && <Spin spinning={loading}>
                    <Form {...formProps} form={form} onAutoSubmit={submit}>
                        <SchemaField schema={schema}/>
                        <div style={{display: "flex", justifyContent: "center"}}>
                            <Submit>提交表单</Submit>
                        </div>
                    </Form>
                </Spin>}

            {
                submitted &&
                renderResult()
            }
        </div>
    )
}
